//
//  CXToolsEntController.swift
//  CXSwiftDemo
//
//  Created by 潮汐 on 2023/12/5.
//

import UIKit

////导入网路请求框架
import Alamofire
import SwiftyJSON

class CXToolsEntController: CXBaseViewController {
    lazy var tableView: UITableView = UITableView(frame: CGRectZero, style: .plain)
    lazy var dataSouce = [CXHomeListModel]()//数据源-数组
    var page = 0
    

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航栏标题
        self.titleNavLabel.text = "swift功能列表页面"
        //创建tablevie
        createTbaleview()
        
        //添加通知
        NotificationCenter.default.addObserver(self, selector:#selector(test1(notification:)), name: Notification.Name("testnotification"), object: nil)
    }
    
    
    //接收通知处理方法
    @objc func test1(notification:Notification){
        let userinfo = notification.userInfo as![String:Any]
        print("收到通知:",userinfo["name"] ?? "")
    }
  
    
    //初始化tableview
    func createTbaleview(){
        tableView.frame = CGRect(x: 0, y: MC_NavHeight, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-MC_NavHeight)
        tableView.tablevieiOS11(tableView: tableView)//iOS11、iPhoneX适配
        tableView.delegate = self//设置代理
        tableView.dataSource = self//设置代理
        //tableview拖动时收起键盘
        //tableView.keyboardDismissMode = .onDrag
        //去掉分割线
        //tableView.separatorStyle = .none
        view.addSubview(tableView)
    }

    //将要出现
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //影藏导航栏
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
        //隐藏tabbar
        self.tabBarController?.tabBar.isHidden = true
        
    }
    //已经出现
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    //将要消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
    }
    
    deinit {
        print("控制器销毁了")
    }
    
    //侧换返回和点击返回按钮都会走这里，控制不走dealloc也会走这里。
    override func didMove(toParent parent: UIViewController?) {
        super.didMove(toParent: parent)
        if parent == nil {
            print("页面pop成功了")
            //销毁通知
            NotificationCenter.default.removeObserver(self)
        }
    }

    
}


////扩展：同一个文件中的extension和写在class里边没什么区别
extension CXToolsEntController: UITableViewDataSource, UITableViewDelegate{
    
    //返回几组
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
    
    //每一组返回几个cell
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }
    
    //每一个cell的高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    //设置组头高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01;
    }
    
    //设置组脚高度
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01;
    }
    
    //设置下分组头，不然顶部会有黑线
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerGroupView = UIView()
        return headerGroupView
    }
    
    //设置下分组脚，不然底部会有黑线
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footGroupView = UIView()
        return footGroupView
    }
    
    //设置cell的UI
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cellXT = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
        if cellXT == nil {
            //cell复用
            cellXT = UITableViewCell(style: .subtitle, reuseIdentifier: "UITableViewCell")
            //忽略点击效果
            cellXT?.selectionStyle = .none
        }
        let cell = cellXT!
        //设置标题
        cell.textLabel?.font = .systemFont(ofSize: 16)
        if indexPath.row==0 {
            cell.textLabel?.text = "网络请求封装"
            
        }else if indexPath.row==1{
            cell.textLabel?.text = "字符串"
        }else if indexPath.row==2{
            cell.textLabel?.text = "闭包传值"
        }else if indexPath.row==3{
            cell.textLabel?.text = "协议代理"
        }else if indexPath.row==4{
            cell.textLabel?.text = "单利"
        }else if indexPath.row==5{
            cell.textLabel?.text = "自己封装的中间弹窗"
        }else if indexPath.row==6{
            cell.textLabel?.text = "UICollectionView"
        }else if indexPath.row==7{
            cell.textLabel?.text = "UICollectionView流式布局"
        }else if indexPath.row==8{
            cell.textLabel?.text = "UIScrollView测试"
        }else if indexPath.row==9{
            cell.textLabel?.text = "UITextField测试"
        }else if indexPath.row==10{
            cell.textLabel?.text = ""
        }
        
        return cellXT!
    }
    
   //每一个cell的点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row==0 {
            var parmDict =  [String: Any]()
            parmDict.updateValue("101040100", forKey: "cityId")
            //封装的网络请求调用
            CXHttpTool.postWithURL(PathUrl: API.weatherapi, Parameters:parmDict, ShowHUD: true, ShowErrorMsg: true) { isSuccess, responseDict in
                //网络请求成功
                print(responseDict)
                
                let dictDataJson = JSON(responseDict)//用json取数据
                let weatherinfo = dictDataJson["weatherinfo"].dictionaryObject ?? [:]
                print("weatherinfo数据是：\(weatherinfo)")
                
                let weather2 = dictDataJson["weatherinfo"]["weather"].stringValue
                print("weather数据是：\(weather2)")
                
                //字典数据转模型
                let models = weatherinfo.kj.model(CXWeatherModel.self)
                
                let WD = models.WD
                let weather = models.weather
                
                print("风力:\(WD) 天气：\(weather ?? "")")
                
                        
            } FailureBlock: { error in
                //网络请求失败
                
            }
        

        }else if indexPath.row==1 {
            
        }else if indexPath.row==2 {
            let testView = CXBlockTestView()
            //self弱引用[weak self]
            testView.getHeaderHeightBlock = {[weak self] (headerHeight: Double, name: String) -> () in
                print("得到头高\(headerHeight)+\(name)")//得到头高200.0+潮汐
            }
            //
            testView.sendValue = {[weak self] in
                print("无参闭包回调了")
            }
            
            //函数参数闭包传值
            testView.callBackBlock { headerHeight, name in
                print("函数参数闭包回调了：\(headerHeight)+\(name)")
            }
            
            //函数参数闭包传值2
            testView.callBackBlockTwo { str, height in
                print("函数参数闭包2回调了：\(str)+\(height)")
            }
            
            testView.loadData(title: "chaoxi") { title in
                print("非逃逸闭包回调了：\(title)")
            }
                  
            //添加数据
            testView.addDataToUI()
        }else if indexPath.row==3 {
            let VC = CXDelegateTestVC()
//            self.navigationController?.pushViewController(VC, animated: true)
            
            UIViewController.getTopVC()?.navigationController?.pushViewController(VC, animated: true)
            
        }else if indexPath.row==4{
            //单利调用1
            let danli = CXUtils.sharedManager
            danli.getString()
            //单利调用2
            CXUtils.sharedManager.getString()
            //单利传值
            CXUtils.sharedManager.name = "潮汐"
            
            //调用只执行一次的代码
           _ = CXToolsEntController.danliTestOnce
                       
            /// 存入token信息  Key值为"token
            let userName = "潮汐"
            UserDefaults.standard.set(userName, forKey: "userNameKey")
            /// 设为已登录  Key值为"isLogin"
            UserDefaults.standard.set(true, forKey: "isLogin")
            UserDefaults.standard.synchronize()
            
            //String类型可能为空，所以需要进行判断或兜底
            var userNameQ = UserDefaults.standard.string(forKey: "userNameKey") ?? ""
            //Bool类型不会为空，可以直接取相应的值
            let isLogin = UserDefaults.standard.bool(forKey: "isLogin")
            
            CXLog("取出：\(userNameQ)" + "\(isLogin)")
            
        }else if indexPath.row==5{
            //中间弹窗
            CXAlertCXCenterView.AlertCXCenterAlertWithController(Controller: nil, Title:"标题", Message:"内容工地工人打工人滚滚滚电话个时高时低广东省广东省管广东省广东省根深蒂固", otherItemArrays: ["取消","确定"], Type: -1) { indexCenter in
                if indexCenter == 0 {
                    print("点击了第1个按钮")
                }else if indexCenter == 1 {
                    print("点击了第2个按钮")
                }
            }
            
//            //系统弹窗
//            CXAlertCXCenterView.AlertSystemCXCenterAlertWithTitle(Controller: nil, Title:"标题", Message:"这是一个系统唐山放松放松电风扇焚烧发电说法三大方法防守打法鼎折覆餗", otherItemArrays: ["取消","确定"], Type: -1) { indexCenter in
//                if indexCenter == 0 {
//                    print("点击了第1个按钮")
//                }else if indexCenter == 1 {
//                    print("点击了第2个按钮")
//                }
//            }
        
        }else if indexPath.row==6{
            let VC = CXCollectionViewTestVC()
            self.navigationController?.pushViewController(VC, animated: true)
            
        }else if indexPath.row==7{
            let VC = WaterFallViewController()
            self.navigationController?.pushViewController(VC, animated: true)
        }else if indexPath.row==8 {
            let VC = ScrollViewTestVC()
            self.navigationController?.pushViewController(VC, animated: true)
        }else if indexPath.row==9 {
            let VC = TextFieldTestVC()
            self.navigationController?.pushViewController(VC, animated: true)
            
        }else if indexPath.row==10 {
            
        }else if indexPath.row==11 {
            
        }else if indexPath.row==12 {
            
        }
    }
    
    //【单利】里面代码App启动后只执行一次
    static var danliTestOnce: Void = {
        print("这部分代码App启动后只执行一次")
    }()
    
}
